package com.data.structure;

public class SingleLinkedList {
    private int length;//链表节点个数
    private Node head;//头节点
    public SingleLinkedList(){
        length = 0;
        head = null;
    }
    private class Node{
        private Object data ;//每个节点的数据
        private Node next;     //每个节点指向下一个节点的连接
        public Node(Object data){
            this.data = data;
        }
    }

    //链表头添加元素
    public Object addHead(Object obj){
        Node newHead = new Node(obj); //定义新节点
        if(length==0){                //链表为空,将该节点设置为头节点
            head = newHead;
        }else{                        //设置新的头部节点
            newHead.next=head;
            head = newHead;
        }
        length++;                       //链表长度+1
        return obj;
    }

    //删除指定元素，成功返回true
    public boolean delete(Object obj){
        if(length==0){
            return false;
        }
        Node previous = head;
        Node current = head;
        while(current.data!=obj){  //数据不等，始终循环
            if(current.next==null){//循环到最后的节点
                return false;
            }else{                 //当不是最后节点，始终变换previous和current指针，令其相差一个Node
                previous = current;
                current = current.next;
            }
        }
        //跳出循环，说明中找到了对应的Node,则进行指针操作,并返回
        //删除的节点为头节点
        if(current == head){
            head = current.next;
            length--;
        }else{//删除的节点不是头节点
            previous.next = current.next;
            length--;
        }
        return true;
    }

    public Node find(Object obj){
        Node  current = head ;
        int tempSize = length;
        while(tempSize>0){
            if(obj.equals(current.data)){
                return  current;
            }else{
                current=current.next;
            }
            tempSize--;
        }
        return null;
    }

    public void iterator(){
        System.out.println("遍历链表");
        Node  current = head ;
        int tempSize = length;
        while(tempSize>0){
            System.out.println(current.data);
            current = current.next;
            tempSize--;
        }
    }


    public  static void main(String[] args){
        SingleLinkedList sll = new SingleLinkedList();
        int max = 127;//请注意，此处的127
        for(int i=0;i<=max;i++){
            sll.addHead(i);
        }
        Node node = sll.find(max);
        System.out.println(node.data);
        System.out.println(sll.delete(max));
        sll.iterator();

    }
}
